<template>
    <v-container>
        <v-timeline
            clipped
            dense
        >
            <v-timeline-item
                class="white--text mb-12"
                color="orange"
                fill-dot
            >
                <v-btn
                    class="mx-0"
                    depressed
                    @click="showAddTrigger"
                >
                    添加触发器
                </v-btn>
                <v-btn
                    :color="connectedColor"
                    class="mx-0 ml-5"
                    depressed
                    @click="connectServer"
                >
                    {{ connected ? '停止' : '启动' }}
                </v-btn>
            </v-timeline-item>
            <v-timeline-item
                v-for="(item, index) in triggers"
                :key="index"
                class="mb-4"
                small
            >
                <v-card class="elevation-2">
                    <v-card-title class="text-h5">
                        <v-tooltip bottom>
                            <template v-slot:activator="{ on, attrs }">
                                        <span
                                            v-bind="attrs"
                                            v-on="on"
                                        >{{ item.topic }}</span>
                            </template>
                            <span>主TOPIC</span>
                        </v-tooltip>
                        <v-btn class="ml-5" color="primary" @click="send(item)">
                            发送
                        </v-btn>
                        <v-text-field
                            v-model="item.interval"
                            class="ml-5"
                            flat
                            hide-details
                            label="发送周期(秒)"
                            solo
                            style="width: 20px;"
                            @keydown.enter="persend(item)"
                        >
                            <template v-slot:append>
                                <v-btn
                                    :loading="item.loading"
                                    class="ml-2"
                                    color="primary"
                                    @click="persend(item)">
                                    定时发送
                                </v-btn>
                            </template>
                        </v-text-field>
                        <v-btn class="ml-2" @click="stopsend(item)">
                            停止发送
                        </v-btn>
                        <v-spacer></v-spacer>
                        <v-btn @click="showEditTrigger(item)">
                            编辑
                        </v-btn>
                        <v-btn class="ml-2" color="error" @click="del(item.id)">
                            删除
                        </v-btn>
                    </v-card-title>
                    <v-card-text>
                        <v-row no-gutters>
                            <v-col>
                                <v-card
                                    class="pa-2"
                                    tile
                                >
                                    <v-card-title>发送内容</v-card-title>
                                    <v-card-text>
                                        <code-editor :read_only="true" :value="item.value"
                                                     style="width:100%"/>
                                    </v-card-text>
                                </v-card>
                            </v-col>
                            <v-col>
                                <v-card
                                    v-if="item.cbtopic"
                                    class="pa-2"
                                    tile
                                >
                                    <v-card-title>触发器@{{ item.cbtopic }}</v-card-title>
                                    <v-card-text>
                                        <code-editor :read_only="true" :value="item.trigger"
                                                     style="width:100%"/>
                                    </v-card-text>
                                </v-card>
                            </v-col>
                        </v-row>
                    </v-card-text>
                </v-card>
            </v-timeline-item>
        </v-timeline>
        <v-dialog
            v-model="addTriggerDialog"
            fullscreen
            hide-overlay
            transition="dialog-bottom-transition"
        >
            <v-card>
                <v-toolbar
                    color="primary"
                    dark
                >
                    <v-btn
                        dark
                        icon
                        @click="addTriggerDialog = false"
                    >
                        <v-icon>fa fa-times</v-icon>
                    </v-btn>
                    <v-toolbar-title>触发器</v-toolbar-title>
                    <v-spacer></v-spacer>
                    <v-toolbar-items>
                        <v-btn
                            text
                            @click="saveTrigger"
                        >
                            保存
                        </v-btn>
                    </v-toolbar-items>
                </v-toolbar>
                <v-card-text>
                    <v-container>
                        <v-form>
                            <v-text-field
                                v-model="editTrigger.topic"
                                label="Topic"
                                placeholder="发送或监听的topic"
                                required
                            ></v-text-field>
                            发送内容:
                            <code-editor
                                v-model="editTrigger.value"
                                style="width: 100%;"
                            />
                            <v-text-field
                                v-model="editTrigger.cbtopic"
                                label="Callback Topic"
                                placeholder="触发后发送的topic"
                                required
                            ></v-text-field>
                            触发器:
                            <code-editor
                                v-model="editTrigger.trigger"
                                style="width: 100%;"
                            />
                        </v-form>
                    </v-container>
                </v-card-text>
            </v-card>
        </v-dialog>
    </v-container>
</template>
<script>
import {Trigger} from '@/utils/dbutils'
import {MqttUtils} from "@/utils/mqttutils";
import CodeEditor from 'simple-code-editor';

const defaultTrigger = {
    pid: '',
    topic: '',
    value: '',
    trigger: '',
    cbtopic: '',
}


export default {
    name: 'Main',
    props: ['project', 'server'],
    components: {
        CodeEditor
    },
    data() {
        return {
            triggers: [],
            connected: false,
            interval: null,
            editTrigger: {},
            mclient: null,
            addTriggerDialog: false,
        }
    },
    methods: {
        async getAllTrigger() {
            if (this.currProject && this.currProject.id) {
                this.triggers = await Trigger.getAll(this.currProject.id)
                console.log(this.triggers)
            }
        },
        async saveTrigger() {
            let trigger = new Trigger(this.currProject.id, this.editTrigger.topic, this.editTrigger.value, this.editTrigger.trigger, this.editTrigger.cbtopic)
            if (this.editTrigger.id) {
                trigger.id = this.editTrigger.id
            }
            await trigger.save()
            await this.getAllTrigger()
            this.resetDefaultTrigger()

        },
        resetDefaultTrigger() {
            this.editTrigger = {...defaultTrigger}
            this.addTriggerDialog = false
        },
        showAddTrigger() {
            if (this.currProject && this.currProject.id) {
                this.resetDefaultTrigger()
                this.addTriggerDialog = true
            }
        },
        showEditTrigger(item) {
            this.editTrigger = {...item}
            this.addTriggerDialog = true
        },
        async del(id) {
            if (id) {
                await Trigger.del(id)
                await this.getAllTrigger()
            }
        },
        connectServer() {
            let _t = this
            if (this.currServer && this.currProject) {
                if (!this.connected) {
                    this.mclient = new MqttUtils(this.currServer.url, this.currServer.uname, this.currServer.passwd)
                    if (this.triggers && this.triggers.length > 0) {
                        this.triggers.forEach(item => {
                            if (item.trigger) {
                                _t.mclient.subscribe(item.topic, item.value, item.trigger, item.cbtopic)
                            }
                        })
                    }
                } else {
                    if (this.mclient) {
                        this.mclient.close()
                        this.mclient = null
                    }
                }
                this.connected = !this.connected
            }
        },
        stopsend(item){
            if (item.int) {
                clearInterval(item.int)
                this.$set(item, 'loading', false)
            }
        },
        persend(item) {
            if(item.interval){
                item.int = setInterval(this.send, item.interval*1000, item);
                this.$set(item, 'loading', true)
            }
        },
        send(item) {
            this.mclient.publish(item.topic, item.value)
        },
        exportData(){

        },
    },
    computed: {
        currProject() {
            if (this.project) {
                return this.project
            }
            return null
        },
        currServer() {
            if (this.server) {
                return this.server
            }
            return null
        },
        connectedColor() {
            if (this.connected) {
                return 'error'
            }
            return 'success'
        },
    },
    filters: {
        beautify: function (value) {
            if (value && typeof value === 'string') {
                let _value = JSON.parse(value)
                return JSON.stringify(_value, null, 2)
            }
            return ''
        }
    },
    watch: {
        currProject(newItem) {
            if (newItem) {
                this.getAllTrigger()
            }
        },
    },
    mounted() {
        this.getAllTrigger()
    }
}
</script>